package day9;

//synchronized实现多线程购买商品
//两个线程 都想买100个商品
//商品总数只有100个
//而且两个线程必须轮流购买
//锁对象.wait()  当线程等待 需要别人等待 释放对象锁
//锁对象.notify()  唤醒随机一个
//锁对象.notifyAll()  唤醒全部
public class Demo4 {
    int sum = 100;

    public synchronized void buy() {
        String name = Thread.currentThread().getName();
        if (sum > 0) {
            sum--;
            System.out.println(name + "购买了商品,剩余:" + sum + "个");
        }
        //wait();
        try {
            this.notify();  //唤醒
            this.wait();    //等待 释放锁
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Demo4 demo4 = new Demo4();
        new Thread(() -> {
            for (int i = 1; i <= 100; i++) {
                demo4.buy();

            }
        }, "hello").start();
        new Thread(() -> {
            for (int i = 1; i <= 100; i++) {
                synchronized (demo4) {
                    String name = Thread.currentThread().getName();
                    if (demo4.sum > 0) {
                        demo4.sum--;
                        System.out.println(name + "购买了商品,剩余:" + demo4.sum + "个");
                    }
                    try {
                        demo4.notify();  //唤醒
                        demo4.wait();    //等待 释放锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "word").start();

    }
}
